import 'package:flutter/material.dart';

import '../../tool/public_tool.dart';

/// FileName separated_row
///
/// @Author lax
/// @Date 2023/3/29
///
/// @Description

class SeparatedRow extends StatelessWidget {
  /// 分隔组件
  final Widget? separator;

  /// 子组件是否使用Expanded包裹
  final bool? expanded;

  final EdgeInsets? margin;
  final EdgeInsets? padding;

  final Color? color;

  final Decoration? decoration;

  final List<Widget>? children;

  final MainAxisAlignment? mainAxisAlignment;
  final CrossAxisAlignment? crossAxisAlignment;

  final MainAxisSize? mainAxisSize;
  final bool? minCrossSize;

  const SeparatedRow({
    super.key,
    this.separator,
    this.expanded = false,
    this.margin,
    this.padding,
    this.color,
    this.decoration,
    this.children,
    this.mainAxisAlignment,
    this.crossAxisAlignment,
    this.mainAxisSize,
    this.minCrossSize,
  });

  @override
  Widget build(BuildContext context) {
    if (minCrossSize == true) {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [body()],
      );
    }
    return body();
  }

  Widget body() {
    final children = newChildren();
    if (children.isEmpty) {
      return const SizedBox();
    }
    if (margin != null ||
        padding != null ||
        color != null ||
        decoration != null) {
      return Container(
        color: color ?? Colors.transparent,
        margin: margin,
        padding: padding,
        decoration: decoration,
        child: Row(
          mainAxisSize: mainAxisSize ?? MainAxisSize.max,
          mainAxisAlignment: mainAxisAlignment ?? MainAxisAlignment.start,
          crossAxisAlignment: crossAxisAlignment ?? CrossAxisAlignment.center,
          children: newChildren(),
        ),
      );
    }
    return Row(
      mainAxisSize: mainAxisSize ?? MainAxisSize.max,
      mainAxisAlignment: mainAxisAlignment ?? MainAxisAlignment.start,
      crossAxisAlignment: crossAxisAlignment ?? CrossAxisAlignment.center,
      children: newChildren(),
    );
  }

  List<Widget> newChildren() {
    final list = children ?? [];
    if (list.isEmpty) {
      return [];
    }

    List<Widget> oldList = [];
    for (int i = 0; i < list.length; i++) {
      if (!widgetIsVisible(list[i])) {
        continue;
      }
      oldList.add(list[i]);
    }

    List<Widget> newList = [];
    if (oldList.isNotEmpty) {
      for (int i = 0; i < oldList.length - 1; i++) {
        if (expanded == true) {
          newList.add(Expanded(child: oldList[i]));
        } else {
          newList.add(oldList[i]);
        }
        if (separator != null) {
          newList.add(separator!);
        }
      }
      if (expanded == true) {
        newList.add(Expanded(child: oldList.last));
      } else {
        newList.add(oldList.last);
      }
    }
    return newList;
  }
}
